package com.hyjx.framework.component.excel;

import com.hyjx.framework.common.util.SpringBeanUtil;
import com.hyjx.framework.component.excel.column.ExcelTemplateColumn;
import com.hyjx.framework.component.excel.column.ExcelTemplateColumnService;
import com.hyjx.framework.component.excel.template.ExcelTemplate;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

/**
 * excel导出的工具类
 */
public class ExportUtil {

    private List datas;
    private List<ExcelTemplateColumn> columns = null;

    public ExportUtil(List datas, String en_module_name) {
        this.datas = datas;
        ExcelTemplateColumnService excelTemplateColumnService = SpringBeanUtil.getBean("excelTemplateColumnService", ExcelTemplateColumnService.class);
        ExcelTemplate et = excelTemplateColumnService.getExcelTemplate(en_module_name);
        ExcelTemplateColumn dfc = new ExcelTemplateColumn();
        dfc.setPub_excel_template_id(et.getPub_excel_template_id());
        columns = excelTemplateColumnService.list(dfc);
    }

    /**
     * 返回ExportUtil实例
     *
     * @param datas          导出基础数据
     * @param en_module_name 对应模板英文名字
     * @return
     */
    public static ExportUtil getInstance(List datas, String en_module_name) {

        return new ExportUtil(datas, en_module_name);

    }

    /**
     * 导出excel文件
     *
     * @return
     */
    public void getDataAsExcel(HttpServletResponse response) {
        XSSFWorkbook wb;
        try {
            wb = new XSSFWorkbook();
            XSSFSheet sheet = wb.createSheet();
            fillHeader(wb, sheet.createRow(0));
            if (datas != null) {
                for (int i = 0; i < datas.size(); i++) {
                    XSSFRow row = sheet.createRow(i + 1);
                    fillExcel(wb, row, i);
                }
            }
            File tmpFile = new File("data.xls");
            FileOutputStream out = new FileOutputStream(tmpFile);
            wb.write(out);
            out.close();
                   /* HttpHeaders headers = new HttpHeaders();
			        String fileName=new String("数据信息.xlsx".getBytes("gbk"),"gbk");//为了解决中文名称乱码问题
			        headers.setContentDispositionFormData("attachment", fileName); 
			        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); 
			        headers.set("pageEncoding", "utf-8");
			       // setHeader("pageEncoding", "utf-8");
			       //byte [] btye= tmpFile
			     return     new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(tmpFile),  
			                                          headers, HttpStatus.OK); */
            String fileName = "数据信息.xlsx";
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/x-download");
            try {
                response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), "ISO8859-1"));
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
            @SuppressWarnings("deprecation")
            OutputStream outp = null;
            FileInputStream in = null;
            try {
                outp = response.getOutputStream();
                in = new FileInputStream(tmpFile);
                byte[] b = new byte[1024];
                int i = 0;
                while ((i = in.read(b)) > 0) {
                    outp.write(b, 0, i);
                }
                outp.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    outp.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 填充excel
     *
     * @param wb
     * @param row
     * @param i   excel行数
     */
    public void fillExcel(XSSFWorkbook wb, XSSFRow row, Integer i) {
        try {
            Class modelClass = null;
            if (this.datas != null)
                modelClass = this.datas.get(0).getClass();

            if (modelClass != null) {
                Field[] fs = modelClass.getDeclaredFields();
                Method[] methods = modelClass.getDeclaredMethods();
                for (Field f : fs) {
                    for (ExcelTemplateColumn dfc : columns) {
                        if (f.getName().equals(dfc.getEn_column_name())) {
                            for (Method mt : methods) {
                                if (mt.getName().toLowerCase().startsWith("get") && mt.getName().toLowerCase().endsWith(f.getName().toLowerCase())) {
                                    mt.setAccessible(true);
                                    XSSFCell cell = row.createCell(Integer.parseInt(dfc.getExcel_field_no()));
                                    cell.setCellValue(mt.invoke(datas.get(i), null) == null ? "" : mt.invoke(datas.get(i), null).toString());
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置excel的表格表头
     *
     * @param wb
     * @param row
     */
    public void fillHeader(XSSFWorkbook wb, XSSFRow row) {
        for (ExcelTemplateColumn dfc : columns) {
            XSSFCell cell = row.createCell(Integer.parseInt(dfc.getExcel_field_no()));
            cell.setCellValue(dfc.getCh_column_name());
        }
		 
/*		 XSSFCell cell = row.createCell(list.size());
		   cell.setCellValue("错误信息");*/
    }
}
